package com.sjh.zlock;

import com.sjh.utils.Constant;
import org.apache.curator.framework.recipes.locks.InterProcessLock;
import org.apache.curator.framework.recipes.locks.InterProcessSemaphoreMutex;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author jack
 * @data 2020/8/18 5:41 下午
 */
@Component
public class ZookeeperDistributedLock implements DistributedZLock {
    @Override
    public void lock(InterProcessLock lock) {
        try {
             lock.acquire();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public InterProcessLock getLock(String lockKey) {
        return new InterProcessSemaphoreMutex(ZKclient.instance.getClient(), lockKey);
    }


    @Override
    public boolean tryLock(InterProcessLock lock, TimeUnit unit, long waitTime) {
        try {
            return lock.acquire(waitTime, unit);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean tryLock(InterProcessLock lock) {
        try {
            lock.acquire(Constant.R_LOCK_DEFAULT_WAIT_TIME, TimeUnit.SECONDS);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public void unlock(InterProcessLock lock) {
        try {
            lock.release();
        } catch (Exception e) {
//            e.printStackTrace();
            System.out.println("解锁失败");
        }
    }

}
